package utils

import (
	"60321/pkg/global"
	"60321/pkg/models"
	"context"
	"log"
	"strconv"
	"time"
)

// StartEnhancedSyncJob 启动增强版同步任务
func StartEnhancedSyncJob(ctx context.Context, interval time.Duration) {
	ticker := time.NewTicker(interval) // 周期性计时，timer 一次性计时
	defer ticker.Stop()
	for {
		select {
		case <-ticker.C:
			if err := BatchSyncStocks(ctx); err != nil {
				log.Printf("Batch sync stocks error: %v", err)
			}
		case <-ctx.Done():
			log.Println("Enhanced sync job stopped")
			return
		}
	}
}

// BatchSyncStocks 批量同步库存
func BatchSyncStocks(ctx context.Context) error {
	// 1. 从Redis Hash获取所有票的库存
	hashKey := "ticket_stocks"
	stocks, err := global.Redis.HGetAll(ctx, hashKey).Result()
	if err != nil {
		return err
	}
	// 2. 批量同步到数据库
	for ticketIDStr, stockStr := range stocks { // key value
		ticketID, err := strconv.ParseInt(ticketIDStr, 10, 64)
		if err != nil {
			log.Printf("Invalid ticket ID %s: %v", ticketIDStr, err)
			continue
		}
		stock, err := strconv.Atoi(stockStr)
		if err != nil {
			log.Printf("Invalid stock value %s for ticket %d: %v", stockStr, ticketID, err)
			continue
		}
		if err := SyncStock(ticketID, stock); err != nil {
			log.Printf("Sync ticket %d stock error: %v", ticketID, err)
			continue
		}
	}
	return nil
}

func SyncStock(id int64, stock int) error {
	if err := global.Db.Model(&models.TicketModel{}).
		Where("id = ?", id).Update("issuance_quantity", stock).Error; err != nil {
		return err
	}
	return nil
}

func GetUserBirthday(chinaID string) time.Time {
	if len(chinaID) != 18 {
		return time.Time{} // Invalid ID
	}
	year, _ := time.Parse("2006", chinaID[6:10])
	month, _ := time.Parse("01", chinaID[10:12])
	day, _ := time.Parse("02", chinaID[12:14])
	return time.Date(year.Year(), month.Month(), day.Day(), 0, 0, 0, 0, time.Local)
}

func CalculateAge(birthDate time.Time) int {
	today := time.Now()
	age := today.Year() - birthDate.Year()
	if today.Month() < birthDate.Month() || (today.Month() == birthDate.Month() && today.Day() < birthDate.Day()) {
		age--
	}
	return age
}
